<!-- 工单处理 -->
<template>
  <el-dialog v-model="dialogVisible" title="工单处理" width="80%" style="max-width: 1200px" draggable @closed="handlerClosed">
    <el-form ref="formRef" style="width: 100%" :model="formData" :rules="formRules" label-width="90px">
      <el-form-item label="标题：">
        {{ formData.name }}
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="类型：">
            <template v-for="item in woCategoryOptions">
              <el-text v-if="item.value === formData.woCategory">{{ item.label }}</el-text>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态：">
            <template v-for="item in woStatusOptions">
              <el-text v-if="item.value === formData.woStatus">{{ item.label }}</el-text>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级：">
            <template v-for="item in woPriorityOptions">
              <el-text v-if="item.value === formData.woPriority">{{ item.label }}</el-text>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述：">
        <Editor ref="editorRef" v-if="description" :read-only="true" :show-toolbar="false" v-model="description" editorHeight="500px" />
      </el-form-item>
      <el-divider />
      <el-form-item label="处理方案：" v-if="formData.woStatus == 0">
        <!-- 工单状态为 0 时，显示激活按钮 -->
        <el-button type="primary" @click="handleClickBtnActive">激活工单</el-button>
      </el-form-item>
      <el-form-item label="解决方案：" v-else-if="formData.woStatus == 1">
        <el-button v-for="item in woSolutionOptions" :key="item.value" plain :type="getWoSolutionType(item.value)" @click="handleSolutionClick(item)">{{ item.label }}</el-button>
      </el-form-item>
      <el-form-item label="处理方案：" v-else-if="formData.woStatus == 2">
        <el-button type="danger" @click="handleClickBtnClose">关闭工单</el-button>
      </el-form-item>
    </el-form>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="50%">
      <img :src="previewImageUrl" style="width: 100%" />
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { FormInstance, UploadUserFile } from 'element-plus'
import * as WorkOrder from '../../api/WorkOrder'
import { woCategoryOptions, woStatusOptions, woPriorityOptions, woSolutionOptions } from './WorkOrderOptions'
import { useUsersStore } from '../../stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWoSolutionType } from './workOrderTypeUtils'
import Editor from '../../components/Editor.vue'
import _ from 'lodash'

// 添加上传相关引用
const fileList = ref<UploadUserFile[]>([])
const uploadLoading = ref(false) // 添加上传状态

const emits = defineEmits(['submited'])

const usersStore = useUsersStore()
// 表单引用
const formRef = ref<FormInstance>()

// 对话框是否显示
const dialogVisible = ref(false)
const description = ref<string | undefined>('')

// 表单数据
const formData = ref({
  id: null as number | null,
  name: null as string | null,
  woCategory: null as string | null,
  userId: null as number | null,
  userName: null as string | null,
  woStatus: null as number | null,
  woPriority: null as number | null,
  woSolution: null as number | null,
  description: undefined as string | undefined, // 修改这一行
  imageUrls: [] as string[], // 用于保存上传图片的URL列表
})

// 表单验证规则
const formRules = ref({
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  woCategory: [{ required: true, message: '请选择类型', trigger: 'change' }],
  woStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

/**
 * 关闭对话框处理函数
 */
const handlerClosed = () => {
  dialogVisible.value = false
  // 清空文件选择
  fileList.value = []
  uploadLoading.value = false
  resetForm(formRef.value)
}

/**
 * 打开对话框
 */
const open = async (val: any) => {
  const { userId, username } = usersStore.user
  formData.value.userId = userId ?? null
  formData.value.userName = username ?? null
  resetForm(formRef.value)

  if (val) {
    console.log(val.id)
    const data = await WorkOrder.getById(val.id)
    console.log('data', data)
    if (data.code === 200) {
      formData.value = data.data
      description.value = _.unescape(data.data.description || '')
      // 如果已有图片，初始化显示
      if (data.data.imageUrls && data.data.imageUrls.length > 0) {
        // 初始化 fileList 显示已有图片
        fileList.value = data.data.imageUrls.map((url: string, index: number) => ({
          name: `image-${index}.jpg`,
          url: url,
          status: 'success',
        }))
      }
    }
  } else {
    resetForm(formRef.value)
  }
  dialogVisible.value = true
}
/**
 * 通用的工单状态更新函数
 * @param confirmMessage - 确认消息
 * @param status - 要更新的状态
 * @param solution - 解决方案（可选）
 */
const updateWorkOrderStatus = async (confirmMessage: string, status: number, solution?: number) => {
  try {
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const params = {
      ...formData.value,
      description: _.escape(description.value),
      woStatus: status,
      ...(solution !== undefined && { woSolution: solution }),
    }

    console.log('params', params)
    const data = await WorkOrder.put(params)

    if (data.code === 200) {
      ElMessage.success(data.msg)
      handlerClosed()
      emits('submited')
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

/**
 * 处理解决方案点击事件
 * @param val - 点击的解决方案对象
 */
const handleSolutionClick = async (val: any) => {
  await updateWorkOrderStatus(`确定 ${val.label} 吗？`, 2, val.value)
}

/**
 * 激活工单处理函数
 */
const handleClickBtnActive = async () => {
  await updateWorkOrderStatus('确定激活工单吗？', 1)
}

/**
 * 关闭工单处理函数
 */
const handleClickBtnClose = async () => {
  await updateWorkOrderStatus('确定关闭工单吗？', 0)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formData.value = {
    id: null,
    name: null,
    woCategory: null,
    userId: null,
    userName: null,
    woStatus: null,
    woPriority: null,
    woSolution: null,
    description: undefined, // 修改这一行

    imageUrls: [],
  }
  formEl.resetFields()
  fileList.value = []
  uploadLoading.value = false
}

defineExpose({ open })

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref('')
</script>

<style lang="scss" scoped>
.file-upload-container {
  width: 100%;
}

.file-input {
  width: 100%;
  padding: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.file-input:hover {
  border-color: #409eff;
}

.file-preview {
  margin-top: 10px;
}

.preview-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.file-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-name {
  font-size: 14px;
  color: #606266;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-progress {
  margin-top: 10px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
